import 'package:flutter/material.dart';
import 'package:flutter_application_1/utils/utils.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class BgPullRefresh extends StatefulWidget {
  final Widget list;

  final RefreshController refreshController;

  final Function onRefresh;

  final ImageProvider? backgroundImage;

  final Widget? mask;

  final Color? color;

  final double? height;

  BgPullRefresh({
    required this.list,
    required this.refreshController,
    required this.onRefresh,
    required this.backgroundImage,
    this.mask,
    this.color,
    this.height,
  });

  @override
  BgPullRefreshState createState() => BgPullRefreshState();
}

class BgPullRefreshState extends State<BgPullRefresh> {
  Offset _offset = Offset.zero;

  double _headerHeight = Utils.navigationBarHeight;

  Color _color = Colors.white;

  late ImageProvider _bgImage;

  // ImageProvider _bgImage = AssetImage(
  //   ImageUtils.wrapAssets('refresh-header-bg.jpg'),
  // );

  // ImageProvider _bgImage = NetworkImage(
  //   'http://attach.bbs.miui.com/forum/201604/23/194545vozf76qdzrcroc7w.jpg',
  // );

  Widget refreshIngIcon({required Color color}) {
    return Container(
      width: 20,
      height: 20,
      child: CircularProgressIndicator(
        valueColor: AlwaysStoppedAnimation<Color>(color),
        strokeWidth: 2,
      ),
    );
  }

  // 刷新提示
  Widget? refreshTip() {
    if (widget.refreshController == null) {
      return null;
    }

    Widget icon = Container();
    String text = '';
    if (widget.refreshController.headerStatus == RefreshStatus.idle) {
      icon = Icon(Icons.arrow_downward, color: _color);
      text = '下拉刷新';
    } else if (widget.refreshController.headerStatus ==
        RefreshStatus.canRefresh) {
      icon = Icon(Icons.refresh, color: _color);
      text = '松开开始刷新';
    } else if (widget.refreshController.headerStatus ==
        RefreshStatus.refreshing) {
      icon = refreshIngIcon(color: _color);
      text = '刷新中';
    } else if (widget.refreshController.headerStatus ==
        RefreshStatus.completed) {
      icon = Icon(Icons.done, color: _color);
      text = '刷新成功';
    }

    return Container(
      height: kToolbarHeight,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(right: 10),
            child: icon,
          ),
          Text(
            text,
            style: TextStyle(
              color: _color,
              fontSize: 16,
              height: 1.3,
            ),
          )
        ],
      ),
    );
  }

  // 生成下拉头部
  Widget pullRefreshHeader() {
    return Container(
      height: _headerHeight + _offset.dy,
      decoration: _bgImage != null
          ? BoxDecoration(
              image: DecorationImage(
                image: _bgImage,
                fit: BoxFit.cover,
                alignment: Alignment.bottomCenter,
              ),
            )
          : null,
      alignment: Alignment.bottomCenter,
      child: refreshTip(),
    );
  }

  // 生成遮挡的头部
  Widget maskHeader() {
    return Container(
      height: _headerHeight,
      color: Colors.white,
      child: widget.mask ?? null,
    );
  }

  void _onRefresh() {
    widget.onRefresh();
  }

  void _onOffsetChange(bool isUp, double offset) {
    if (isUp) {
      setState(() {
        _offset = Offset.zero.translate(0, offset);
      });
    }
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.color != null) {
      _color = widget.color!;
    }

    if (widget.backgroundImage != null) {
      _bgImage = widget.backgroundImage!;
    } else {
      // 没有背景字体用黑色
      _color = Colors.black;
    }

    if (widget.height != null) {
      _headerHeight = widget.height!;
    }

    double opacity = 1 - (_offset.dy / 20);
    if (opacity < 0.0) {
      opacity = 0.0;
    } else if (opacity > 1.0) {
      opacity = 1.0;
    }

    return Scaffold(
      body: RefreshConfiguration.copyAncestor(
        context: context,
        // 头部触发刷新的越界距离
        headerTriggerDistance: _headerHeight,
        // 头部最大可以拖动的范围
        maxOverScrollExtent: _headerHeight * 1.5,
        child: Stack(
          children: <Widget>[
            Column(
              children: <Widget>[
                Container(height: _headerHeight),
                Expanded(
                  flex: 1,
                  child: SmartRefresher(
                    controller: widget.refreshController,
                    enablePullDown: true,
                    onRefresh: _onRefresh,
                    onOffsetChange: _onOffsetChange,
                    header: CustomHeader(
                      height: _headerHeight,
                      builder: (_, __) => Container(),
                    ),
                    child: widget.list,
                  ),
                )
              ],
            ),
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: Opacity(
                opacity: 1 - opacity,
                child: pullRefreshHeader(),
              ),
            ),
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: Opacity(
                opacity: opacity,
                child: maskHeader(),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
